import React, { FC, useContext } from 'react'
import { Avatar, IconCheckbox } from '../../../components'
import { Wrap, IconRemove, IconPause, IconStart } from './style'
import { PollTerModel } from '../translator'
import { PollContext } from '../index'
import shallow from 'zustand/shallow'
import { usePollStore } from '../store'

export const ListItem: FC<PollTerModel> = ({ mcc, status: { checked }, number, mtKey }) => {
	const { state, cur_poll_mt, list, toggleClick, toggleCtrl, toggleShift } = usePollStore(
		(state) => ({
			list: state.list,
			state: state.state,
			cur_poll_mt: state.cur_poll_mt,
			toggleClick: state.toggleClick,
			toggleCtrl: state.toggleCtrl,
			toggleShift: state.toggleShift,
		}),
		shallow
	)
	const { remove, handleClickLi } = useContext(PollContext)
	let _index = list.findIndex((item) => item.mtKey === mtKey) + 1
	const show_position = _index < 10 ? '0' + _index : _index + ''
	const indexWidth = (show_position as string).length * 8
	/**当前终端是否是被轮询到的对象 */
	let _flag = false
	if (cur_poll_mt) {
		_flag = cur_poll_mt.mt_key === mtKey ? true : false
	} else {
		_flag = false
	}
	const handleCheckItem = (e: React.MouseEvent) => {
		if (e.ctrlKey) {
			toggleCtrl(mtKey)
		} else if (e.shiftKey) {
			toggleShift(mtKey)
		} else {
			toggleClick(mtKey)
		}
	}
	const handleMultiCheck = (e: React.MouseEvent) => {
		e.stopPropagation()
		toggleCtrl(mtKey)
	}
	const handleRemove = (e: React.MouseEvent) => {
		e.stopPropagation()
		remove(mtKey)
	}
	return (
		<Wrap
			checked={checked}
			indexWidth={indexWidth}
			title={mcc.name}
			onClick={handleCheckItem}
			flag={_flag}
			onDoubleClick={handleClickLi}
		>
			<div className="checkbox-wrap" onClick={handleMultiCheck}>
				<IconCheckbox className="icon-checkbox" />
			</div>
			<div className="poll_item_position">{show_position}</div>
			<div className="avatar">
				<Avatar value={mcc} />
			</div>
			<div className="name">
				{state === 1 && _flag && <IconStart></IconStart>}
				{state === 2 && _flag && <IconPause></IconPause>}
				<div className={`poll_item_name`}>{mcc.name}</div>
			</div>
			<IconRemove className="remove" onClick={handleRemove} />
		</Wrap>
	)
}
